<?php
/**
 * Access.php
 * 
 * @category    Madoqua
 * @package     Controller
 * @subpackage  Plugin
 */

/** base class */
require_once 'Zend/Controller/Plugin/Abstract.php';

/** zend auth */
require_once 'Zend/Auth.php';

/**
 * Madoqua_Controller_Plugin_Access
 * 
 * this seems more than adequate, binary exclusion of non-admins, no ACL needed.
 * 
 * @category    Madoqua
 * @package     Controller
 * @subpackage  Plugin
 */
class Madoqua_Controller_Plugin_Access extends Zend_Controller_Plugin_Abstract 
{
    /**
     * first dispatch hook
     *
     * @param Zend_Controller_Request_Abstract $request
     */
    public function dispatchLoopStartup(Zend_Controller_Request_Abstract $request) 
    {
        if ($request->isXmlHttpRequest()) {
            $request->setParam('format', 'html');
            //use html content by default
        }
        
        if (!Madoqua_Application::isInstalled() && $request->getModuleName() != 'install') {
            //application hasn't been installed yet :(
            $request->setModuleName('install');
            $request->setControllerKey('index');
            $request->setActionName('index');
            //forward to installer module
        }
    }
    
    /**
     * predispatch hook
     *
     * @param Zend_Controller_Request_Abstract $request
     */
    public function preDispatch(Zend_Controller_Request_Abstract $request)
    {
        if (Madoqua_Application::isInstalled() && in_array($request->getModuleName(), Madoqua_Application::getAdminModules())) {
            //this request is for an admin module
            if (!Zend_Auth::getInstance()->hasIdentity()) {
                //but we don't have access to that, uh ohw
                $request->setModuleName('auth');
                $request->setControllerName('auth');
                $request->setActionName('login');
                //redirect to auth/auth/login
                
                Zend_Layout::getMvcInstance()->setLayout('admin/login');
                //use login layout
            }
        }
    }
}